package org.loy.eclipse.post_debug_perspective;

import org.eclipse.debug.core.DebugEvent;
import org.eclipse.debug.core.IDebugEventSetListener;
import org.eclipse.debug.core.model.IProcess;
import org.eclipse.jface.preference.IPreferenceStore;

import org.loy.eclipse.post_debug_perspective.preferences.PreferenceConstants;

public class DebugEventListener implements IDebugEventSetListener
{
	@Override
	public void handleDebugEvents(DebugEvent[] events) {
		for (DebugEvent event : events) {
			dispatchEvent(event);
		}
	}
	
	private void dispatchEvent(DebugEvent event)
	{
		// lazy preferences store initialization
		if (store == null) {
			store = Activator.getDefault().getPreferenceStore();
		}

		// check is enabled
		if (!store.getBoolean(PreferenceConstants.P_IS_ENABLED)) {
			return ;
		}
		
		IProcess process;

		// do checks
		// TODO check, maybe debug session not always finishes with process termination
		// (consider case of remote debuggers, or something like this...)
		if (event.getSource() instanceof IProcess) {
			process = (IProcess)event.getSource();
		} else {
			return ;
		}
		
		if (event.getKind() != DebugEvent.TERMINATE) {
			return ;
		}

		if (!process.getLaunch().getLaunchMode().equals("debug")) {
			return ;
		}
		
		// switch to perspective
		String perspective = store.getString(PreferenceConstants.P_PERSPECTIVE_TO_SET);
		if (perspective.equals(PreferenceConstants.DO_NOT_SWITCH_PERSPECTIVE)) {
			return ;
		}

		// TODO check is perspective currently available
		
		SetPerspectiveJob job = new SetPerspectiveJob(perspective);
		job.schedule();
	}

	private IPreferenceStore store;
}
